package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.chlid

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.QMUIDisplayHelper
import com.example.library_common.view.bubblelayout.BubbleLayout
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.AgencySubPageInfo
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.bean.AgencyMySpotBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.bean.AgencyMySpotItemBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.AGENCY_APPLYING_INTENT_TO_AGENCY_MY_SPOT
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.AGENCY_MY_SPOT_TO_APPLYING_PAGE
import com.example.shushiyunsst.util.HiDataBus
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import com.example.wallet.utils.Preference
import com.senon.modularapp.util.JssSpannableString
import ikidou.reflect.TypeBuilder
import java.lang.reflect.Type

/**
 *我的地盘
 * */
class AgencyMySpotFragment : SimpleListFragment<AgencyMySpotItemBean>(), AgencySubPageInfo {


    companion object {
        fun newInstance(): AgencyMySpotFragment {
            val args = Bundle()
            val fragment = AgencyMySpotFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override val title = R.string.agency_my_spot

    override val icon = R.mipmap.agency_my_spot

    private var mMySpotBean: AgencyMySpotBean? = null

    private val iconMoney = AppGlobals.getApplication().getString(R.string.wallet_sst)

    private var isRefreshing = false

    private lateinit var listHeader: View

    private var mHeaderView: BubbleLayout? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
        isAddDividerItemDecoration = false
        isAlwaysRefresh = false
        isEnableLoadMore = false
//        isInitialRefresh = false
    }


    override fun initView(view: View) {
        super.initView(view)
        mRecyclerView.overScrollMode = View.OVER_SCROLL_NEVER
        mRecyclerView.clipToPadding = false
        mRecyclerView.setPadding(0, 0, 0, QMUIDisplayHelper.dp2px(_mActivity, 4))

        HiDataBus.with<String>(AGENCY_APPLYING_INTENT_TO_AGENCY_MY_SPOT)
            .observerSticky(this, false, {
                if (!mSwipeRefreshLayout.isRefreshing) {
                    mSwipeRefreshLayout.isRefreshing = true
                    onRefresh()
                }
            })

        addListHeaderView()

        list_empty_view.removeAllViews()
        addEmptyView(R.layout.fragment_agency_my_content_frame_spot)
    }

    override fun onRefresh() {
        isRefreshing = true
        super.onRefresh()
    }

    override fun getItemLayout(): Int {
        return R.layout.fragment_agency_my_spot
    }

    override fun convertItem(helper: JssBaseViewHolder?, item: AgencyMySpotItemBean?) {
        helper?.setText(R.id.account, "${item?.account}")
            ?.setText(R.id.createTime, "${item?.createTime}")
            ?.setText(R.id.txNum, "${item?.txNums} ${item?.tokenType}")
            ?.setText(R.id.income, "${item?.income} ${item?.tokenType}")
            ?.setText(R.id.logType, "${item?.logType}")
            ?.setText(R.id.statusDesc, "${item?.statusDesc}")
    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(AgencyMySpotItemBean::class.java).endSubType().build()
    }

    override fun netRequest() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val deviceTokens = Preference.HOLDER.getCustomAppProfile(CURRENT_DEVICE_TOKEN)
        RestClient.builder()
            .url(R.string.queryMyProxy)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "deviceToken" to "$deviceTokens",
                        "uid" to "${userInfo?.uid}"
                    )
                )
            )
            .success {
//                Log.d("onViewCreated", "onViewCreated: $it")
                isRefreshing = false
                parseDate(it)
            }
            .failure {
                isRefreshing = false
                onFailed()
            }
            .error { _, _ ->
                isRefreshing = false
                onFailed()
            }.build().post()
    }

    override fun parseDate(data: String?) {
//        super.parseDate(data)
        mMySpotBean = JSON.parseObject(data, AgencyMySpotBean::class.java)

        loadListDate(mMySpotBean?.proxyIncomeLog)
//        loadListDate(emptyList())

        setListHeaderView()
    }

    private fun addListHeaderView() {
        mAdapter.removeAllHeaderView()
        listHeader = LayoutInflater.from(_mActivity)
            .inflate(R.layout.fragment_agency_my_header_spot, list_empty_view, false)

        mAdapter.addHeaderView(listHeader)
        mHeaderView = listHeader.findViewById(R.id.mHeaderView)

        mHeaderView?.visibility = View.GONE
    }

    @SuppressLint("SetTextI18n")
    private fun setListHeaderView() {
        val mArea: TextView? = listHeader.findViewById(R.id.mArea)
        val mAccIncome: TextView? = listHeader.findViewById(R.id.mAccIncome)


        val value = "${mMySpotBean?.totalIncome} $iconMoney"
        val target = "零售服务总收益: $value"

        mArea?.text = "当前代理区域：${mMySpotBean?.areaNameFull}"
        mAccIncome?.text = JssSpannableString(_mActivity, target)
            .first(value).size(16).textColor(R.color.PrimaryColor)

//        mHeaderView?.measure(0, 0)
        val offset = QMUIDisplayHelper.dp2px(_mActivity, 78)
        val screenWidth = QMUIDisplayHelper.getScreenWidth(_mActivity)
        mHeaderView?.arrowPosition = (screenWidth-offset) * 1.0f

        if (mMySpotBean?.isProxy == 0) {
            mHeaderView?.visibility = View.GONE
        } else {
            mHeaderView?.visibility = View.VISIBLE
        }
    }


    override fun preEmptyView() {


        val applying: View = list_empty_view.findViewById(R.id.applying)

        applying.setOnClickListener {
            HiDataBus.with<String>(AGENCY_MY_SPOT_TO_APPLYING_PAGE)
                .postStickyData("")
        }
    }

    override fun onFailed() {
        super.onFailed()
        mAdapter.isUseEmpty = mMySpotBean?.isProxy == 0
    }
}